package com.sailboard.iot.opm.web.controller;

import com.github.pagehelper.PageInfo;
import com.rabbitmq.client.AMQP;
import com.sailboard.iot.opm.common.DataGrid;
import com.sailboard.iot.opm.common.JsonResult;
import com.sailboard.iot.opm.common.ResultCode;
import com.sailboard.iot.opm.dao.entity.Account;
import com.sailboard.iot.opm.dao.entity.ConsumeRecord;
import com.sailboard.iot.opm.dao.entity.User;
import com.sailboard.iot.opm.service.AccountService;
import com.sailboard.iot.opm.service.ConsumeRecordService;
import com.sailboard.iot.opm.service.UserService;
import com.sailboard.iot.opm.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/")
public class ConsumeRecordController {
    @Resource
    ConsumeRecordService consumeRecordService;

    @Resource
    UserService userService;

    @Resource
    AccountService accountService;

    private User getCurrent_user(){
        User current_user=new User();
        Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser != null && currentUser.getPrincipals() != null) {
            String username = currentUser.getPrincipals().toString();
            current_user = userService.getByUsername(username);
        }
        return current_user;
    }

    @RequestMapping(value = "v1/api0/consume_Record/list")
    @ResponseBody
    public DataGrid listConsume_Record(Integer page, Integer rows, ConsumeRecord consumeRecord){
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        PageInfo pageInfo = consumeRecordService.getConsume_RecordList(page,rows,consumeRecord);
        return  new DataGrid(pageInfo);
    }

    /**
     * 拒绝提现
     * @param recordID
     * @return
     */
    @RequestMapping(value = "v1/api0/withdraw/disAgree",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult disAgree(String recordID){
        if (StringUtils.isBlank(recordID)){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        String remarks = "提现拒绝";
        boolean isSuccess = consumeRecordService.updateStatus(Long.valueOf(recordID),1,remarks);
        return (isSuccess) ? JsonResult.success() : JsonResult.error();
    }

    /**
     * 同意提现
     * @param recordID
     * @return
     */
    @RequestMapping(value = "v1/api0/withdraw/agree", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult agree(String recordID,Long accountID,BigDecimal amount){
        if (StringUtils.isBlank(recordID)){
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, ResultCode.PARAM_ERROR_MSG);
        }
        String remarks = "同意提现";
        boolean isSuccess = consumeRecordService.updateStatus(Long.valueOf(recordID),1,remarks);
        Account account = accountService.getAccountByID(accountID);
        account.setProfit(account.getProfit().subtract(amount));
        accountService.updateAccount(account);
        return (isSuccess) ? JsonResult.success() : JsonResult.error();
    }

    /**
     * 获取公司的提现记录
     * @param page
     * @param rows
     * @param consumeRecord
     * @return
     */
    @RequestMapping(value = "v1/api0/withdrawal/application", method = RequestMethod.POST)
    @ResponseBody
    public DataGrid<PageInfo> withDrawalApplicationList(Integer page, Integer rows, ConsumeRecord consumeRecord){
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        consumeRecord.setCreaterId(this.getCurrent_user().getCompanyId());//用createrId暂存公司登陆人所属id。
        PageInfo pageInfo = consumeRecordService.getWithdrawalApplication(page, rows, consumeRecord);
        return new DataGrid(pageInfo);
    }

    /**
     * 判断是否有提现申请还未处理
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping(value = "v1/api0/launch/application", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult launchApplication(Integer page, Integer rows){
        page = page == null ? 1 : page;
        rows = rows == null ? 10 : rows;
        ConsumeRecord consumeRecord = new ConsumeRecord();
        consumeRecord.setCreaterId(this.getCurrent_user().getCompanyId());//用createrId暂存公司登陆人所属id。
        PageInfo pageInfo = consumeRecordService.getWithdrawalApplication(page, rows, consumeRecord);
        List<ConsumeRecord> recordList = pageInfo.getList();
        boolean isProcessing = false;
        for(ConsumeRecord cr : recordList){
            if(cr.getStatus() == Byte.valueOf("2")){
                isProcessing = true;
                break;
            }
        }
        if(isProcessing){
            return new JsonResult(ResultCode.ERROR_CODE, "您还有未被处理的申请，请勿重复提交");
        }else{
            return JsonResult.success();
        }
    }

    /**
     * 获取可提现金额
     * @return
     */
    @RequestMapping(value = "v1/api0/launch/profitBalance", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getBalanceForWithdrawal(){
        BigDecimal profitBalance = accountService.getAccountByUserId(Long.valueOf(this.getCurrent_user().getCompanyId())).getProfit();//收益账户余额。
        return  new JsonResult(ResultCode.SUCCESS_CODE, ResultCode.SUCCESS_MSG,profitBalance);
    }

    /**
     * 提交提现申请
     * @param consumeRecord
     * @return
    */
    @RequestMapping(value = "v1/api0/application/submit", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult submitApplication(ConsumeRecord consumeRecord){
        if(!(consumeRecord.getAmount().compareTo(BigDecimal.ZERO) == 1)){//小于或者等于0
            return new JsonResult(ResultCode.ERROR_CODE,"提现金额必须为正数");
        }
        BigDecimal profitBalance = accountService.getAccountByUserId(Long.valueOf(this.getCurrent_user().getCompanyId())).getProfit();//收益账户余额。
        if(consumeRecord.getAmount().compareTo(profitBalance) == 1){//提现大于余额。
            return new JsonResult(ResultCode.ERROR_CODE,"提现金额不得超出余额");
        }
        consumeRecord.setStatus(Byte.valueOf("2"));//状态为申请中
        consumeRecord.setCreaterId(this.getCurrent_user().getId());//创建人为登陆者
        consumeRecord.setCreater(this.getCurrent_user().getRealName());
        consumeRecord.setAccountId(accountService.getAccountByUserId(Long.valueOf(this.getCurrent_user().getCompanyId())).getId());//账户为登陆人所在公司的账户
        consumeRecord.setType(Byte.valueOf("2"));//消费类型为提现
        consumeRecord.setAccount_type("3");//账户类型设置为收益账户
        consumeRecord.setName("提现申请");
        boolean isSuccess = consumeRecordService.addConsumeRecordWithdrawal(consumeRecord);
        return isSuccess ? JsonResult.success() : JsonResult.error();
    }

}
